<!doctype html>



  


<html class="theme-next muse use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="spring boot," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="本篇介绍在SpringBoot中配置Email服务的具体步骤，以及常见的异常分析。具体案例以QQ邮箱以及QQ企业邮箱为例。


QQ邮箱发送方式
QQ企业邮箱发送方式
总结


tips:下面提到的hashIndex指的是一个元素put到hashmap中时，要根据其key.hashcode &amp;amp; (table.size()-1)来决定其在table中的位置。
table是一个数组，类型为N">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot配置Email发送功能详解">
<meta property="og:url" content="http://yoursite.com/2016/08/28/spring-boot-mail/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="本篇介绍在SpringBoot中配置Email服务的具体步骤，以及常见的异常分析。具体案例以QQ邮箱以及QQ企业邮箱为例。


QQ邮箱发送方式
QQ企业邮箱发送方式
总结


tips:下面提到的hashIndex指的是一个元素put到hashmap中时，要根据其key.hashcode &amp;amp; (table.size()-1)来决定其在table中的位置。
table是一个数组，类型为N">
<meta property="og:image" content="http://b.hiphotos.baidu.com/zhidao/wh%3D600%2C800/sign=6979b0ff307adab43d851345bbe49f24/c2cec3fdfc03924547e8e2d88194a4c27c1e2583.jpg">
<meta property="og:image" content="http://images.cnitblog.com/blog/466768/201304/15225614-98d3fdf2080b400e81a8b21433bf4a6b.jpg">
<meta property="og:updated_time" content="2017-01-19T07:14:13.664Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringBoot配置Email发送功能详解">
<meta name="twitter:description" content="本篇介绍在SpringBoot中配置Email服务的具体步骤，以及常见的异常分析。具体案例以QQ邮箱以及QQ企业邮箱为例。


QQ邮箱发送方式
QQ企业邮箱发送方式
总结


tips:下面提到的hashIndex指的是一个元素put到hashmap中时，要根据其key.hashcode &amp;amp; (table.size()-1)来决定其在table中的位置。
table是一个数组，类型为N">
<meta name="twitter:image" content="http://b.hiphotos.baidu.com/zhidao/wh%3D600%2C800/sign=6979b0ff307adab43d851345bbe49f24/c2cec3fdfc03924547e8e2d88194a4c27c1e2583.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2016/08/28/spring-boot-mail/"/>

  <title> SpringBoot配置Email发送功能详解 | 个人博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">个人博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">随便写点什么</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                SpringBoot配置Email发送功能详解
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-28T15:53:48+08:00" content="2016-08-28">
              2016-08-28
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/spring-boot/" itemprop="url" rel="index">
                    <span itemprop="name">spring boot</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/08/28/spring-boot-mail/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/08/28/spring-boot-mail/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <hr>
<p>本篇介绍在SpringBoot中配置Email服务的具体步骤，以及常见的异常分析。<br>具体案例以QQ邮箱以及QQ企业邮箱为例。</p>
<blockquote>
<ul>
<li>QQ邮箱发送方式</li>
<li>QQ企业邮箱发送方式</li>
<li>总结</li>
</ul>
</blockquote>
<p>tips:<br>下面提到的hashIndex指的是一个元素put到hashmap中时，要根据其key.hashcode &amp; (table.size()-1)来决定其在table中的位置。</p>
<p>table是一个数组，类型为Node。Node是hashmap的一个内部类，用来描述hashmap的元素的一些属性。</p>
<hr>
<a id="more"></a>
<h2 id="1-相关依赖包"><a href="#1-相关依赖包" class="headerlink" title="1.相关依赖包"></a>1.相关依赖包</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">parent</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.3.0.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">parent</span>&gt;</span></div><div class="line"></div><div class="line"> <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></div><div class="line">        <span class="comment">&lt;!-- springBoot--&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.3.0.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line">        <span class="comment">&lt;!-- email --&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-mail<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line">        <span class="comment">&lt;!-- html模板 --&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-velocity<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></div></pre></td></tr></table></figure>
<p>SpringBoot以及mail的依赖包就不做解释了。<br>这里简单介绍下velocity的作用：<br>Velocity 是一个基于 Java 的模板引擎框架，提供的模板语言可以使用在 Java 中定义的对象和变量上。<br>作为邮件模板也是它的一个主要应用场景。<br>具体用法在下面会进行说明。</p>
<hr>
<h2 id="2-具体案例"><a href="#2-具体案例" class="headerlink" title="2.具体案例"></a>2.具体案例</h2><p>###1.使用QQ邮箱进行发送<br>application.properties<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">#发送邮箱（可以填你自己的邮箱）</div><div class="line">email.from = xxxxxxx@qq.com</div><div class="line">#目标邮箱</div><div class="line">email.to = </div><div class="line">#邮箱服务器</div><div class="line">email.host = smtp.qq.com</div><div class="line">#授权码，在QQ邮箱客户端生成</div><div class="line">email.auth = kpzmxhrkqklwbbbd</div></pre></td></tr></table></figure></p>
<p>大家可能不理解auth授权码是干什么用的。<br>这相当于是当以第三方形式登录时用非密码验证的一种手段。<br>在QQ邮箱-&gt;设置-&gt;账户 往下拉可以找到。<br>同时需要把POP3/SMTP服务开启。<br><img src="http://b.hiphotos.baidu.com/zhidao/wh%3D600%2C800/sign=6979b0ff307adab43d851345bbe49f24/c2cec3fdfc03924547e8e2d88194a4c27c1e2583.jpg" alt="授权码"></p>
<hr>
<p>JavaMailSender<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</div><div class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</div><div class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</div><div class="line"><span class="keyword">import</span> org.springframework.core.env.Environment;</div><div class="line"><span class="keyword">import</span> org.springframework.mail.javamail.JavaMailSender;</div><div class="line"><span class="keyword">import</span> org.springframework.mail.javamail.JavaMailSenderImpl;</div><div class="line"></div><div class="line"><span class="keyword">import</span> javax.mail.Authenticator;</div><div class="line"><span class="keyword">import</span> javax.mail.PasswordAuthentication;</div><div class="line"><span class="keyword">import</span> java.util.Properties;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * author   : qianweifeng</div><div class="line"> * date     : 16/4/9.</div><div class="line"> * describe :</div><div class="line"> */</div><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MailConfig</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> Environment env;</div><div class="line"></div><div class="line">    <span class="meta">@Bean</span>(name = <span class="string">"JavaMailSender"</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> JavaMailSender <span class="title">getSender</span><span class="params">()</span></span>&#123;</div><div class="line">        JavaMailSenderImpl javaMailSender = <span class="keyword">new</span> JavaMailSenderImpl();</div><div class="line">        javaMailSender.setUsername(env.getProperty(ConfigConstant.EMAIL_FROM));</div><div class="line">        javaMailSender.setHost(env.getProperty(ConfigConstant.EMAIL_HOST));</div><div class="line">        javaMailSender.setPort(<span class="number">587</span>);<span class="comment">//①</span></div><div class="line">        javaMailSender.setDefaultEncoding(<span class="string">"UTF-8"</span>);</div><div class="line">        Properties props = <span class="keyword">new</span> Properties();<span class="comment">//②</span></div><div class="line">        props.setProperty(<span class="string">"mail.smtp.host"</span>, env.getProperty(ConfigConstant.EMAIL_HOST));</div><div class="line">        props.setProperty(<span class="string">"mail.smtp.auth"</span>, <span class="string">"true"</span>);</div><div class="line">        javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,<span class="keyword">new</span> Authenticator()&#123;</div><div class="line">            <span class="meta">@Override</span></div><div class="line">            <span class="function"><span class="keyword">protected</span> PasswordAuthentication <span class="title">getPasswordAuthentication</span><span class="params">()</span></span>&#123;</div><div class="line">                <span class="keyword">return</span> <span class="keyword">new</span> PasswordAuthentication(<span class="string">"xxxxxx@qq.com"</span>,env.getProperty(ConfigConstant.EMAIL_AUTH));</div><div class="line">            &#125;</div><div class="line">        &#125;);</div><div class="line">        javaMailSender.setSession(session);<span class="comment">//③</span></div><div class="line">        <span class="keyword">return</span> javaMailSender;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这是Java邮件发送的一个具体实现Bean。<br>关于JavaMailSender的内容大家自行看源码或者度娘。<br>这里说明3个方面。<br>1.javaMailSender.setPort(587) 这个端口不是随意设置的，根据邮箱服务器以及协议来定的。我在网上找了相关资料，大家参考下：<br><img src="http://images.cnitblog.com/blog/466768/201304/15225614-98d3fdf2080b400e81a8b21433bf4a6b.jpg" alt=""></p>
<p>2.关于Properties的设置。这里只需要设置其邮箱服务器以及启用授权码验证方式即可。</p>
<p>3.session完成的使用授权码验证邮件发送方，相当于建立起一个有效会话。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> com.service.config.ConfigConstant;</div><div class="line"><span class="keyword">import</span> org.slf4j.Logger;</div><div class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</div><div class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</div><div class="line"><span class="keyword">import</span> org.springframework.context.SmartLifecycle;</div><div class="line"><span class="keyword">import</span> org.springframework.core.env.Environment;</div><div class="line"><span class="keyword">import</span> org.springframework.mail.javamail.JavaMailSender;</div><div class="line"><span class="keyword">import</span> org.springframework.mail.javamail.MimeMessageHelper;</div><div class="line"><span class="keyword">import</span> org.springframework.mail.javamail.MimeMessagePreparator;</div><div class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</div><div class="line"></div><div class="line"><span class="keyword">import</span> javax.mail.internet.MimeMessage;</div><div class="line"><span class="keyword">import</span> java.util.concurrent.Executors;</div><div class="line"><span class="keyword">import</span> java.util.concurrent.ScheduledExecutorService;</div><div class="line"><span class="keyword">import</span> java.util.concurrent.TimeUnit;</div><div class="line"><span class="keyword">import</span> java.util.concurrent.atomic.AtomicInteger;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * author   : qianweifeng</div><div class="line"> * date     : 16/4/9.</div><div class="line"> * describe :</div><div class="line"> */</div><div class="line"><span class="meta">@Component</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MailUtil</span> <span class="keyword">implements</span> <span class="title">SmartLifecycle</span> </span>&#123;</div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> JavaMailSender javaMailSender;</div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> Environment env;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> Logger logger = LoggerFactory.getLogger(MailUtil.class);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> ScheduledExecutorService service = Executors.newScheduledThreadPool(<span class="number">2</span>);</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AtomicInteger count = <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> MimeMessagePreparator <span class="title">Send</span><span class="params">(<span class="keyword">final</span> String text)</span> </span>&#123;</div><div class="line">        MimeMessagePreparator preparator = <span class="keyword">new</span> MimeMessagePreparator() &#123;</div><div class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">prepare</span><span class="params">(MimeMessage mimeMessage)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">                MimeMessageHelper message = <span class="keyword">new</span> MimeMessageHelper(mimeMessage);</div><div class="line">                message.setTo(env.getProperty(ConfigConstant.EMAIL_TO));</div><div class="line">                message.setFrom(env.getProperty(ConfigConstant.EMAIL_FROM));</div><div class="line">                message.setSubject(<span class="string">"java email send test"</span>);</div><div class="line"><span class="comment">//                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/report.vm", "UTF-8", model);</span></div><div class="line">                message.setText(text, <span class="keyword">true</span>);</div><div class="line">            &#125;</div><div class="line">        &#125;;</div><div class="line">        <span class="keyword">return</span> preparator;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isAutoStartup</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stop</span><span class="params">(Runnable runnable)</span> </span>&#123;</div><div class="line"></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> </span>&#123;</div><div class="line">        service.scheduleWithFixedDelay(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">            <span class="meta">@Override</span></div><div class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">                <span class="keyword">try</span> &#123;</div><div class="line">                    <span class="keyword">if</span> (count.get() == <span class="number">2</span>) &#123;</div><div class="line">                        service.shutdown();</div><div class="line">                        logger.info(<span class="string">"the task is down"</span>);</div><div class="line">                    &#125;</div><div class="line">                    logger.info(<span class="string">"start send email and the index is "</span> + count);</div><div class="line"></div><div class="line">                    javaMailSender.send(Send(<span class="string">"test !"</span> + <span class="string">"*"</span> + count.getAndIncrement()));</div><div class="line"></div><div class="line">                    logger.info(<span class="string">"send email success"</span>);</div><div class="line">                &#125;<span class="keyword">catch</span> (Exception e)&#123;</div><div class="line">                    logger.error(<span class="string">"send email fail"</span> , e);</div><div class="line">                &#125;</div><div class="line"></div><div class="line">            &#125;</div><div class="line">        &#125;,<span class="number">2000</span>,<span class="number">2000</span>, TimeUnit.MILLISECONDS);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stop</span><span class="params">()</span> </span>&#123;</div><div class="line"></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isRunning</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getPhase</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="number">0</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>使用方式：<br>将邮件服务器，授权码，发送方，接受放在application.properties配置好。<br>项目启动后就会开始发送，总共发送2封邮件。</p>
<p>使用velocity来构建邮件正文<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">send</span><span class="params">(<span class="keyword">final</span> String date, <span class="keyword">final</span> String date2)</span> </span>&#123;</div><div class="line">      </div><div class="line">     </div><div class="line">        <span class="keyword">final</span> List&lt;UVBean&gt; uVBean = getUV(start, end);</div><div class="line">        <span class="keyword">final</span> List&lt;UserResAndLoginReport&gt; resAndLoginReports = dao.RegisterAndLogin(start, end);</div><div class="line"></div><div class="line">        Map model = <span class="keyword">new</span> HashMap();</div><div class="line">        model.put(<span class="string">"uVBean"</span>, uVBean);</div><div class="line">        model.put(<span class="string">"resAndLoginReports"</span>, resAndLoginReports);</div><div class="line">                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, <span class="string">"velocity/report.vm"</span>, <span class="string">"UTF-8"</span>, model);</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">h3</span>&gt;</span>1.UV<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">TABLE</span> <span class="attr">border</span>=<span class="string">"1px"</span> <span class="attr">style</span>=<span class="string">"border-collapse: collapse;"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">TR</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">td</span> <span class="attr">nowrap</span>=<span class="string">"nowarp"</span> <span class="attr">style</span>=<span class="string">"width:80px;"</span> <span class="attr">class</span>=<span class="string">"date"</span>&gt;</span>日期<span class="tag">&lt;/<span class="name">td</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">td</span> <span class="attr">nowrap</span>=<span class="string">"nowarp"</span> <span class="attr">style</span>=<span class="string">"width:120px;"</span> <span class="attr">class</span>=<span class="string">"head"</span>&gt;</span>UV<span class="tag">&lt;/<span class="name">td</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">TR</span>&gt;</span></div><div class="line">    #foreach( $data in $uVBean )</div><div class="line">        <span class="tag">&lt;<span class="name">TR</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">TD</span> <span class="attr">nowrap</span>=<span class="string">"nowarp"</span> <span class="attr">class</span>=<span class="string">"date"</span>&gt;</span>$&#123;data.date&#125;<span class="tag">&lt;/<span class="name">TD</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">TD</span> <span class="attr">nowrap</span>=<span class="string">"nowarp"</span> <span class="attr">class</span>=<span class="string">"count"</span>&gt;</span>$&#123;data.data&#125;<span class="tag">&lt;/<span class="name">TD</span>&gt;</span></div><div class="line">        <span class="tag">&lt;/<span class="name">TR</span>&gt;</span></div><div class="line">    #end</div><div class="line"><span class="tag">&lt;/<span class="name">TABLE</span>&gt;</span></div><div class="line">...</div></pre></td></tr></table></figure>
<p>假设我们需要在邮件中显示的一些复杂内容，可以后台以对象的形式包装起来，放入一个hashmap中，在velocity解析出来，至于如何解析，那就是velocity的语义的问题了。<br>使用velocity可以在邮件正文中以html的方式来丰富化邮件。<br><a href="http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/" target="_blank" rel="external">可以参考这篇文章</a></p>
<p>###2.使用QQ企业邮箱进行发送<br>过程以及代码几乎相同<br>区别是邮件服务器为：smtp.exmail.qq.com或者pop.exmail.qq.com<br>没有授权码这一概念。<br>发送端口号25或者SMTP协议下端口为465，POP协议下端口为995。<br>推荐验证方式为直接用户名+密码，或者用ssl方式进行验证。<br>具体参考<a href="http://service.exmail.qq.com/cgi-bin/help?id=28" target="_blank" rel="external">腾讯企业邮箱客户端设置</a><br>给出一个简单的样例：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">JavaMailSenderImpl javaMailSender = <span class="keyword">new</span> JavaMailSenderImpl();</div><div class="line">       javaMailSender.setUsername(env.getProperty(<span class="string">"spring.mail.username"</span>));</div><div class="line">       javaMailSender.setHost(env.getProperty(<span class="string">"spring.mail.host"</span>));</div><div class="line">       javaMailSender.setPassword(env.getProperty(<span class="string">"spring.mail.password"</span>));</div><div class="line">       javaMailSender.setPort(<span class="number">25</span>);</div><div class="line">       javaMailSender.setDefaultEncoding(<span class="string">"UTF-8"</span>);</div><div class="line">       javaMailSender.send(preparator);</div></pre></td></tr></table></figure></p>
<p>preparator就是上面出现过的MimeMessagePreparator的实例。配置方法见上。</p>
<h2 id="3-总结"><a href="#3-总结" class="headerlink" title="3.总结"></a>3.总结</h2><blockquote>
<p>1.发送邮件我们首要配置的包括：邮箱服务器，协议，端口。<br>2.一般验证有两种方式，一种是直接的用户名密码，另一种是通过授权码或者ssl进行验证。<br>3.邮件的正文可以是纯文本，或者是html内容，html内容可以由velocity模板构建或者直接用字符串构建出html内容。</p>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/spring-boot/" rel="tag">#spring boot</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/28/spring-boot-1/" rel="next" title="spring boot实战（1）">
                <i class="fa fa-chevron-left"></i> spring boot实战（1）
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/28/Java垃圾回收机制/" rel="prev" title="Java垃圾回收机制">
                Java垃圾回收机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/08/28/spring-boot-mail/"
           data-title="SpringBoot配置Email发送功能详解" data-url="http://yoursite.com/2016/08/28/spring-boot-mail/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/touxiang.jpg"
               alt="钱伟峰" />
          <p class="site-author-name" itemprop="name">钱伟峰</p>
          <p class="site-description motion-element" itemprop="description">每天进步一点点</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">21</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-相关依赖包"><span class="nav-number">1.</span> <span class="nav-text">1.相关依赖包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-具体案例"><span class="nav-number">2.</span> <span class="nav-text">2.具体案例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-总结"><span class="nav-number">3.</span> <span class="nav-text">3.总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">钱伟峰</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"qianweifeng"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  

  

  

  

</body>
</html>
